import {AfterViewInit, Component, OnInit} from '@angular/core';
import {GridOptions} from '@ag-grid-community/core';
import {ApiService} from '@core/services/http/api.service';
import {GridConfigService} from '@core/config/grid-config.service';
import {DatePipe} from "@angular/common";
import {ApesMessageService} from "@shared/apes/message";

@Component({
  selector: 'complaint-rate',
  templateUrl: './complaint-rate.component.html',
  styleUrls: ['./complaint-rate.component.scss'],
})
export class ComplaintRateComponent implements OnInit, AfterViewInit {
  buttonBar = [{hide: true, style: 'default', label: '查询', id: 'action_query'}];
  title = '';
  ctx = {model: {}};

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = 240 + 'px';

  hind: string = 'none';
  startDate: Date = null;
  endDate: Date = null;
  nowDay = new Date();

  chart: any;
  bodyStyle = {padding: 0};

  // carData: any[];
  // notCarData: any[];
  // nullData: any[] = [];
  g2Data: any;


  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private datePipe: DatePipe, private msg: ApesMessageService) {
    this.columnDefs = [
      {'headerName': '月份', field: 'MONTH', width: 70},
      {'headerName': '投诉量', field: 'TSL', width: 85},
      {'headerName': '洗车美容投诉', field: 'XCMRTS', width: 120},
      {'headerName': '洗车台次', field: 'XCMRTC', width: 100},
      {'headerName': '投诉率', field: 'XCMRTSL', width: 85},
      {'headerName': '非洗车投诉', field: 'FXCMRTS', width: 110},
      {'headerName': '非洗车台次', field: 'FXCMRTC', width: 110},
      {'headerName': '投诉率', field: 'FXSMRTSL', width: 85}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 15,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
  }

  ngOnInit() {
    this.endDate = new Date(this.nowDay.setMonth(this.nowDay.getMonth() - 1));
    this.startDate = new Date(this.nowDay.setMonth(this.nowDay.getMonth() - 11));
    this.submit();

  }

  ngAfterViewInit() {
  }

  getBar() {
    let charts: any;
    charts = new G2.Chart({
      container: 'mountNode',
      forceFit: true,
      height: 240,
      padding: {top: 30, right: 45, bottom: 85, left: 45}
    });


    charts.axis('XCMRTSL', {
      grid: null,
      label: {
        textStyle: {
          textAlign: 'top',
          fill: '#fdae6b',
        },
      },
    });
    charts.legend({
      custom: true,
      allowAllCanceled: true,
      items: [{
        value: '洗车美容投诉',
        marker: {
          symbol: 'square',
          fill: '#3182bd',
          radius: 5,
        },
      }, {
        value: '投诉率',
        marker: {
          symbol: 'hyphen',
          stroke: '#fdae6b',
          radius: 5,
          lineWidth: 3,
        },
      }]
    });
    const defs = {
      'XCMRTSL': {
        alias: '投诉率',
      },
      'XCMRTS': {
        alias: '洗车美容投诉'
      }
    };
    charts.source(this.rowData, defs);
    charts.interval().position('MONTH*XCMRTS').color('#3182bd');
    charts.line().position('MONTH*XCMRTSL').color('#fdae6b').size(3).shape('smooth');
    charts.point().position('MONTH*XCMRTSL').color('#fdae6b').size(3).shape('circle');
    charts.render();

    if (this.chart) {
      this.chart.destroy();
    }
    this.chart = charts;
  };

  getCar() {
    let charts: any;
    charts = new G2.Chart({
      container: 'content',
      forceFit: true,
      height: 240,
      padding: {top: 30, right: 45, bottom: 85, left: 45}
    });
    charts.axis('FXSMRTSL', {
      grid: null,
      label: {
        textStyle: {
          textAlign: 'top',
          fill: '#1de9b6',
        },
      },
    });
    charts.legend({
      custom: true,
      allowAllCanceled: true,
      items: [{
        value: '非洗车美容投诉',
        marker: {
          symbol: 'square',
          fill: '#d500f9',
          radius: 5,
        },
      }, {
        value: '投诉率',
        marker: {
          symbol: 'hyphen',
          stroke: '#1de9b6',
          radius: 5,
          lineWidth: 3,
        },
      }]
    });
    const def = {
      'FXSMRTSL': {
        alias: '投诉率',
      },
      'FXCMRTS': {
        alias: '非洗车美容投诉'
      }
    };
    charts.source(this.rowData, def);
    charts.interval().position('MONTH*FXCMRTS').color('#d500f9');
    charts.line().position('MONTH*FXSMRTSL').color('#1de9b6').size(3).shape('smooth');
    charts.point().position('MONTH*FXSMRTSL').color('#1de9b6').size(3).shape('circle');


    charts.render();
    if (this.g2Data) {
      this.g2Data.destroy();
    }
    this.g2Data = charts;
  }

  getTablesData(start, end) {
    let data = {'START_DATE': start, 'END_DATE': end};
    this.apiService.post('crm.customComplain.queryComplainRateReport', {'body': JSON.stringify(data)}).subscribe(
      (body) => {
        if (body) {
          //  将年月份排序
          // console.log(body)
          for (let i = 0, len = body.length; i < len; i++) {
            body[i]['MONTH'] = new Date(body[i]['MONTH']);
          }
          body = body.sort(this.sortarr('MONTH'));
          // 将排好序的数组赋给data
          let data = body;
          for (let i = 0, len = data.length; i < len; i++) {
            data[i]['MONTH'] = this.datePipe.transform(new Date(body[i]['MONTH']), 'yyyy/MM');
          }

          this.rowData = data;
          if( this.rowData.length === 0 ) {
            this.msg.info(`未找到满足条件的数据`);
          }

          this.getBar();
          this.getCar();
        } else {
          this.msg.info(body.msg);
        }
      });
  }

// 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

// 日期相减
  getTimeChang(end, start) {
    let mon = 24 * 60 * 60 * 1000 * 30;
    try {
      let dateArr = end.toISOString().slice(0, 7).split('-');
      let checkDate = new Date(new Date(new Date().toLocaleDateString()).getTime());
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1);
      let checkTime = checkDate.getTime();

      let dateArr2 = start.toISOString().slice(0, 7).split('-');
      let checkDate2 = new Date(new Date(new Date().toLocaleDateString()).getTime());
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1);
      let checkTime2 = checkDate2.getTime();
      let days = (checkTime - checkTime2) / mon;
      if (days < 12) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }


  onEvent(data:any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.submit();
      }
    }
  }

  submit() {
    if (this.startDate !== null && this.endDate !== null) {
      let ts = new Date(this.startDate.toLocaleDateString()).getTime();
      let te = new Date(this.endDate.toLocaleDateString()).getTime();
      let now = new Date(new Date().toLocaleDateString()).getTime();
      if (ts !== now && te !== now) {
        let startDate = this.startDate.toISOString().slice(0, 7);
        let endDate = this.endDate.toISOString().slice(0, 7);
        if (this.getTimeChang(this.endDate, this.startDate) === 'show') {
          this.hind = 'block';
        } else {
          this.hind = 'none';
          this.getTablesData(startDate, endDate);
        }
      } else {
        this.hind = 'block';
      }
    } else {
      this.hind = 'block';
    }
  }

}
